package com.echoesnet.echoesshortvideo.Activities;

import android.app.Activity;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.Selection;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.echoesnet.echoesshortvideo.AppController;
import com.echoesnet.echoesshortvideo.Beans.UserBean;
import com.echoesnet.echoesshortvideo.Constant.EsvConstant;
import com.echoesnet.echoesshortvideo.R;
import com.echoesnet.echoesshortvideo.Utils.CdnUtils.CdnHelper;
import com.echoesnet.echoesshortvideo.Utils.CdnUtils.IOnCdnFeedbackListener;
import com.echoesnet.echoesshortvideo.Utils.Cryptology.MD5Util;
import com.echoesnet.echoesshortvideo.Utils.Image.GlideApp;
import com.echoesnet.echoesshortvideo.Utils.SharePreUtils;
import com.echoesnet.echoesshortvideo.Utils.ToastUtils;
import com.echoesnet.echoesshortvideo.View.MaxByteLengthEditText;
import com.echoesnet.echoesshortvideo.ViewModels.UserDetailViewModel;
import com.echoesnet.echoesshortvideo.views.dialog.CustomAlertDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.orhanobut.logger.Logger;
import com.soundcloud.android.crop.Crop;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;

import org.json.JSONObject;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.qqtheme.framework.entity.City;
import cn.qqtheme.framework.entity.County;
import cn.qqtheme.framework.entity.Province;
import cn.qqtheme.framework.picker.AddressPicker;
import cn.qqtheme.framework.picker.DatePicker;
import cn.qqtheme.framework.picker.DateTimePicker;
import cn.qqtheme.framework.picker.OptionPicker;
import cn.qqtheme.framework.util.ConvertUtils;
import cn.qqtheme.framework.widget.WheelView;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import me.iwf.photopicker.PhotoPicker;

public class MyEditAct extends BaseActivity
{
    private static final String TAG = MyEditAct.class.getSimpleName();
    private static final int MAX_NUM=20;

    @BindView(R.id.tv_back)
    ImageView tvBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_save)
    TextView tvSave;
    @BindView(R.id.iv_pic)
    ImageView ivPic;
    @BindView(R.id.iv_canmara)
    ImageView ivCamera;
    @BindView(R.id.rl_pic)
    RelativeLayout rlPic;
    @BindView(R.id.et_nickname)
    MaxByteLengthEditText etNickname;
    @BindView(R.id.tv_gender)
    TextView tvGender;
    @BindView(R.id.tv_birthday)
    TextView tvBirthday;
    @BindView(R.id.tv_city)
    TextView tvCity;
    @BindView(R.id.et_signture)
    EditText etSignture;

    private Unbinder unbinder;
    private Activity mAct;
    private UserDetailViewModel uViewModel;
    private Observable observable;
    private String[] gender;
    private UserBean userBean;

    private String headImgUrl = "";
    private String msgDigest;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_edit);
        unbinder = ButterKnife.bind(this);
        initView();
    }

    private void initView()
    {
        mAct = this;
        etNickname.setMaxByteLength(MAX_NUM);
        userBean = new UserBean();
        uViewModel = ViewModelProviders.of(this).get(UserDetailViewModel.class);
        uViewModel.getUserDetail().observe(this, new Observer<UserBean>()
        {
            @Override
            public void onChanged(@Nullable UserBean user)
            {
                userBean.setHeadPic(user.getHeadPic());
                userBean.setSignature(user.getSignature());
                userBean.setSex(user.getSex());
                userBean.setBirthday(user.getBirthday());
                userBean.setNickname(user.getNickname());
                userBean.setCity(user.getCity());
                if (user != null)
                {
                    Logger.t(TAG).d(user.toString());
                    etSignture.setText(TextUtils.isEmpty(user.getSignature()) ? "未填写" : user.getSignature());
                    tvCity.setText(TextUtils.isEmpty(user.getCity()) ? "未填写" : user.getCity());
                    etNickname.setText(TextUtils.isEmpty(user.getNickname()) ? "用户123456" : user.getNickname());
                    tvGender.setText(TextUtils.isEmpty(user.getSex()) ? "未填写" : user.getSex());
                    tvBirthday.setText(TextUtils.isEmpty(user.getBirthday()) ? "未填写" : user.getBirthday());
                    headImgUrl=user.getHeadPic();
                    etNickname.setSelection(etNickname.getText().toString().trim().length());
//                    if (TextUtils.isEmpty(user.getHeadPic()))
//                    {
//                        ivCamera.setVisibility(View.VISIBLE);
//                    } else
//                    {
//                        ivCamera.setVisibility(View.GONE);
//                    }
                    GlideApp.with(AppController.getInstance())
                            .load(user.getHeadPic())
                            .circleCrop()
                            .error(R.drawable.default_80px)
                            .into(ivPic);
                    msgDigest= getMsgDigest(user.getHeadPic());
                }
                //设置新光标所在的位置
                Selection.setSelection(etNickname.getText(), etNickname.getText().length());
            }
        });
        uViewModel.requestUserDetail(SharePreUtils.getUId());

        uViewModel.updateUserDetail().observe(this, new Observer<String>()
        {
            @Override
            public void onChanged(@Nullable String user)
            {
                Logger.t(TAG).d(user.toString());
                ToastUtils.showShort("修改成功");
                finish();
            }
        });
        gender = getResources().getStringArray(R.array.myinfo_gender);
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        if (unbinder != null)
            unbinder.unbind();
        if (observable != null)
            observable.unsubscribeOn(Schedulers.io());
    }

    @OnClick({R.id.tv_back, R.id.tv_save, R.id.iv_pic, R.id.rl_pic, R.id.et_nickname, R.id.tv_gender, R.id.tv_birthday, R.id.tv_city, R.id.et_signture})
    public void onClick(View view)
    {
        switch (view.getId())
        {
            case R.id.tv_back:
                try
                {
                    if (getMsgDigest(headImgUrl).equals(msgDigest))
                    {
                        finish();
                        break;
                    }
                } catch (Exception e)
                {
                    e.printStackTrace();
                }

                new CustomAlertDialog(MyEditAct.this)
                        .builder()
                        .setTitle("提示")
                        .setMsg("是否放弃保存修改")
                        .setPositiveButton("保存", new View.OnClickListener()
                        {
                            @Override
                            public void onClick(View v)
                            {
                               saveUserInfo();
                            }
                        })
                        .setPositiveTextColor(ContextCompat.getColor(mAct, R.color.C0321))
                        .setNegativeButton("放弃", new View.OnClickListener()
                        {
                            @Override
                            public void onClick(View v)
                            {
                                finish();
                            }
                        })
                        .setNegativeTextColor(ContextCompat.getColor(mAct, R.color.C0322))
                        .show();
                break;
            case R.id.tv_save://保存修改资料
                saveUserInfo();
                break;
            case R.id.iv_pic:
            case R.id.rl_pic://换头像
                chooseHeadPic();
                break;
            case R.id.et_nickname:
                break;
            case R.id.tv_gender:
                showChoiceGenderDialog();
                break;
            case R.id.tv_birthday://生日
                setNewBirthdayPicker(tvBirthday);
                break;
            case R.id.tv_city://城市
                setCityOption(tvCity);
                break;
            case R.id.et_signture:
                break;
        }
    }

    private void saveUserInfo()
    {
        UserBean bean = new UserBean();
        String sex = tvGender.getText().toString().trim();
        String nickName = etNickname.getText().toString().trim();
        String city = tvCity.getText().toString().trim();
        String birthDay=tvBirthday.getText().toString().trim();
        String signature = etSignture.getText().toString().trim();
        bean.setSex("未填写".equals(sex)?"":"男".equals(sex) ? "1" : "0");
        bean.setNickname("用户123456".equals(nickName)?"":nickName);// 昵称
        bean.setCity("未填写".equals(city)?"":city);// 城市
        bean.setBirthday("未填写".equals(birthDay)?"":birthDay);// 生日
        bean.setHeadPic(headImgUrl);// 头像
        bean.setSignature("未填写".equals(signature)?"":signature);//签名
        if (TextUtils.isEmpty(nickName.trim()))
        {
            ToastUtils.showShort("昵称不能为空。");
            return;
        }
        uViewModel.updateUserInfo(bean);
    }


    private void showChoiceGenderDialog()
    {
        OptionPicker statePicker = new OptionPicker(this, gender);
        int positon = 0;
        if (userBean == null)
            return;
        if (userBean.getSex().equals("0"))
        {
            positon = 0;
        }
        else
        {
            positon = 1;
        }
        statePicker.setSelectedIndex(positon);
        //  statePicker.setSelectedIndex(0);
        setOptionPicker(statePicker, tvGender);

    }

    /**
     * 选项选择器
     *
     * @param optionPicker
     * @param textView
     */
    private void setOptionPicker(OptionPicker optionPicker, final TextView textView)
    {
        optionPicker.setCycleDisable(true);
        optionPicker.setLineVisible(true);
        optionPicker.setShadowVisible(false);
        optionPicker.setTopLineVisible(false);
        optionPicker.setTopLineHeight(1);
        cn.qqtheme.framework.widget.WheelView.LineConfig config = new cn.qqtheme.framework.widget.WheelView.LineConfig();
        config.setColor(0xFF33B5E5);//线颜色
        config.setAlpha(140);//线透明度
        config.setRatio((float) (1.0 / 100.0));//线比率
        optionPicker.setLineConfig(config);
        //  optionPicker.setTopLineColor(0xFF33B5E5);
        optionPicker.setCancelTextColor(0xFF33B5E5);
        optionPicker.setCancelTextSize(13);
        optionPicker.setSubmitTextColor(0xFF33B5E5);
        optionPicker.setSubmitTextSize(13);
        optionPicker.setItemWidth(200);
        optionPicker.setTextSize(14);
        optionPicker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener()
        {
            @Override
            public void onOptionPicked(int index, String item)
            {
                textView.setText(item);
            }
        });
        optionPicker.show();
    }

    private int getItem(TextView veiw, List listText)
    {

        for (int i = 0; i < listText.size(); i++)
        {
            if (veiw.getText().toString().equals(listText.get(i)))
                return i;
        }
        return 2;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent result)
    {
        switch (requestCode)
        {
            case EsvConstant.EAM_TAKE_PHOTO_FROM_GALLERY:
                if (resultCode == RESULT_OK)
                {
                    ArrayList<String> mResults = result.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                    Logger.t(TAG).d("图片地址：" + mResults.get(0));
                    beginCrop(Uri.fromFile(new File(mResults.get(0))));
                }
                break;
            case CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE:
                handleCrop(resultCode, result);
                break;

        }
    }

    private void beginCrop(Uri source)
    {
        CropImage.activity(source)
                .setGuidelines(CropImageView.Guidelines.ON)
                .setCropShape(CropImageView.CropShape.OVAL)
                .setAspectRatio(1, 1)
                .start(this);
    }

    private void handleCrop(int resultCode, Intent result)
    {
        if (resultCode == RESULT_OK)
        {
            CropImage.ActivityResult cropResult = CropImage.getActivityResult(result);
            uploadHeadImg(cropResult.getUri());
        }
        else if (resultCode == Crop.RESULT_ERROR)
        {
            String error = Crop.getError(result).getMessage();
            Logger.t(TAG).d("拍照返回错误信息--> " + error);
            if (TextUtils.isEmpty(error))
            {
                ToastUtils.showShort("照片裁剪失败");
            }
            else if (error.toLowerCase().contains("gif"))
            {
                ToastUtils.showShort("不能使用GIF图片");
            }
            else
            {
                ToastUtils.showShort(error);
            }
        }
    }

    private void uploadHeadImg(final Uri inputUri)
    {
        String fileKeyName = CdnHelper.userImage + UUID.randomUUID().toString().substring(0, 8) + ".jpg";
        CdnHelper.getInstance().setOnCdnFeedbackListener(new CdnFeedbackListener(this, inputUri));
        ivPic.setBackground(ContextCompat.getDrawable(this, R.drawable.shape_circle_c0412_bg));
        CdnHelper.getInstance().putFile(new File(inputUri.getPath()), "img", fileKeyName, 0);
    }

    private static class CdnFeedbackListener implements IOnCdnFeedbackListener
    {
        private final WeakReference<MyEditAct> mActRef;
        private Uri imgUri;

        private CdnFeedbackListener(MyEditAct mAct, Uri imgUri)
        {
            this.mActRef = new WeakReference<MyEditAct>(mAct);
            this.imgUri = imgUri;
        }

        @Override
        public void onSuccess(JSONObject response, File file, String fileKeyName, int uploadOrder)
        {
            final MyEditAct cAct = mActRef.get();
            if (cAct != null)
            {
                Logger.t(TAG).d("成功：" + response.toString());
                GlideApp.with(AppController.getInstance())
                        .load(imgUri)
                        .circleCrop()
                        .into(cAct.ivPic);
                cAct.headImgUrl = CdnHelper.CDN_ORIGINAL_SITE + fileKeyName;
            }
        }

        @Override
        public void onProcess(long len)
        {

        }

        @Override
        public void onFail(JSONObject response, File file)
        {
            final MyEditAct cAct = mActRef.get();
            if (cAct != null)
            {
                Logger.t(cAct.TAG).d("错误：" + response.toString());
            }
        }
    }

    /**
     * 头像选择器
     */
    private void chooseHeadPic()
    {
        PhotoPicker.builder()
                .setPhotoCount(1)
                .setPreviewEnabled(true)
                .setShowCamera(true)
                .setShowGif(false)
                .setShowImgFromCamera(true)
                .start(mAct, EsvConstant.EAM_TAKE_PHOTO_FROM_GALLERY);
    }


    /**
     * 生日选择器
     */
    private void setNewBirthdayPicker(final TextView birth)
    {
        int year = Calendar.getInstance().get(Calendar.YEAR) - 99;
        int month = 3;
        int day = 3;

        String[] text = birth.getText().toString().split("-");
        if (text.length == 3)
        {
            try
            {
                if (Integer.parseInt(text[0]) >= year)
                    year = Integer.parseInt(text[0]);

                if (Integer.parseInt(text[0]) > Calendar.getInstance().get(Calendar.YEAR) - 10)
                    year = Calendar.getInstance().get(Calendar.YEAR) - 10;

                month = Integer.parseInt(text[1]);
                day = Integer.parseInt(text[2]);
            } catch (NumberFormatException e)
            {
                e.printStackTrace();
            }
        }

        DatePicker picker = new DatePicker(this, DateTimePicker.YEAR_MONTH_DAY);
        picker.setCycleDisable(true);
        picker.setDividerVisible(true);
        picker.setTopLineVisible(false);
        picker.setShadowVisible(false);
        picker.setTitleText("选择生日");
        picker.setTitleTextSize(14);
        picker.setTitleTextColor(ContextCompat.getColor(this, R.color.C0321));
        picker.setTitleTextColor(ContextCompat.getColor(this, R.color.C0311));
        picker.setTitleTextColor(ContextCompat.getColor(this, R.color.C0311));
        picker.setTopLineVisible(false);
        picker.setRangeStart(Calendar.getInstance().get(Calendar.YEAR) - 99, 1, 1);
        picker.setRangeEnd(Calendar.getInstance().get(Calendar.YEAR) - 10, Calendar.getInstance().get(Calendar.MONTH) + 1, Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
        picker.setSelectedItem(year, month, day);
        WheelView.DividerConfig config1 = new WheelView.DividerConfig();
        config1.setColor(0xFF33B5E5);//线颜色
        config1.setAlpha(140);//线透明度
        config1.setRatio((float) (1.0));//线比率
        picker.setDividerConfig(config1);

        picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener()
        {
            @Override
            public void onDatePicked(String year, String month, String day)
            {
                birth.setText(year + "-" + month + "-" + day);
            }
        });
        picker.show();
    }

    private void setCityOption(final TextView tvCity)
    {
        observable = Observable.create(new ObservableOnSubscribe<ArrayList<Province>>()
        {
            @Override
            public void subscribe(ObservableEmitter<ArrayList<Province>> e) throws Exception
            {
                ArrayList<Province> data = new ArrayList<>();
                String json = ConvertUtils.toString(MyEditAct.this.getAssets().open("city.json"));
                data.addAll((ArrayList<Province>) new Gson().fromJson(json, new TypeToken<ArrayList<Province>>()
                {
                }.getType()));
                e.onNext(data);
                e.onComplete();
            }
        });
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new io.reactivex.Observer<ArrayList<Province>>()
                {
                    private Disposable disposable;

                    @Override
                    public void onSubscribe(Disposable d)
                    {
                        disposable = d;
                    }

                    @Override
                    public void onNext(ArrayList<Province> provinces)
                    {
                        if (provinces.size() > 0)
                        {
                            AddressPicker picker = new AddressPicker(mAct, provinces);
                            picker.setHideProvince(false);
                            picker.setHideCounty(true);
                            picker.setTopLineVisible(false);
                            picker.setTitleText("选择城市");
                            picker.setCancelTextColor(ContextCompat.getColor(mAct, R.color.C0311));
                            picker.setTitleTextSize(14);
                            picker.setSubmitTextColor(ContextCompat.getColor(mAct, R.color.C0311));
                            // picker.setColumnWeight(1 / 3.0, 2 / 3.0);//将屏幕分为3份，省级和地级的比例为1:2
                            picker.setSelectedItem("北京", "北京", "");
                            picker.setOnAddressPickListener(new AddressPicker.OnAddressPickListener()
                            {
                                @Override
                                public void onAddressPicked(Province province, City city, County county)
                                {
                                    tvCity.setText(city.getAreaName());
                                }
                            });
                            picker.show();
                        }
                        else
                        {
                            ToastUtils.showShort("数据初始化失败");
                        }
                    }

                    @Override
                    public void onError(Throwable e)
                    {
                        Logger.t(TAG).d("e>" + e);
                    }

                    @Override
                    public void onComplete()
                    {
                        Logger.t(TAG).d("city's data parse has completed");
                    }
                });
    }

    private String getMsgDigest(String ...input)
    {
        StringBuilder sb=new StringBuilder();
        for (String s : input)
        {
            sb.append(s);
        }
        try
        {
            String str=sb.toString()+etNickname.getText()+tvGender.getText()+
                                        tvBirthday.getText()+tvCity.getText()+etSignture.getText();
            Logger.t(TAG).d(str);
            return MD5Util.MD5(str);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return "";
    }

}
